package deleteface.bank.jqsoft.cn.deleteface;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.bugly.Bugly;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.request.RequestCall;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jqsoft.bank.deleteface.R;
import deleteface.bank.jqsoft.cn.deleteface.ui.WebServiceUtils;

public class DeleteFaceForSingle extends Fragment {
    RequestCall call;
    Button btnDeleteArchive,btn_delete_time,btn_add_area,btn_ip_list;
    EditText etIdCardToDelete;
    TextView ip_address,ip_time;
    ArrayList<IpBean> urlList=new ArrayList<>();
    ArrayList<IpBean> timeurlList=new ArrayList<>();
    String timeurl="";
    String url = "";
    String message;
    AlertDialog dialog;
    String[] item;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container, false);

        urlList.add(new IpBean("固镇","http://218.22.110.114:8801/delete",
                "http://218.22.110.114:9093/fdss-api/face/delReadCardInfoByCardNo","218.22.110.114"));
        urlList.add(new IpBean("肥东","http://218.22.56.86:8801/delete",
                "http://218.22.56.86:9093/fdss-api/face/delReadCardInfoByCardNo","218.22.56.86"));
        urlList.add(new IpBean("泗县","http://60.171.220.164:8801/delete"
                ,"http://60.171.220.164:9093/fdss-api/face/delReadCardInfoByCardNo","60.171.220.164"));
        urlList.add(new IpBean("铜官","http://60.173.1.131:8801/delete",
                "http://60.173.1.131:9093/fdss-api/face/delReadCardInfoByCardNo","60.173.1.131"));
        urlList.add(new IpBean("濉溪","http://117.57.168.206:8801/delete",
                "http://117.57.168.206:9093/fdss-api/face/delReadCardInfoByCardNo","117.57.168.206"));
        urlList.add(new IpBean("太湖","http://183.167.230.159:8801/delete",
                "http://183.167.230.159:9093/fdss-api/face/delReadCardInfoByCardNo","183.167.230.159"));
        urlList.add(new IpBean("岳西","http://60.171.137.137:8801/delete",
                "http://60.171.137.137:9093/fdss-api/face/delReadCardInfoByCardNo","60.171.137.137"));
        urlList.add(new IpBean("舒城","http://60.173.152.105:8801/delete",
                "http://60.173.152.105:9093/fdss-api/face/delReadCardInfoByCardNo","60.173.152.105"));
        urlList.add(new IpBean("颍上","http://220.179.65.153:8801/delete",
                "http://220.179.65.153:9093/fdss-api/face/delReadCardInfoByCardNo","220.179.65.153"));
        urlList.add(new IpBean("颍东","http://220.179.84.235:8801/delete",
                "http://220.179.84.235:9093/fdss-api/face/delReadCardInfoByCardNo","220.179.84.235"));
        urlList.add(new IpBean("太和","http://220.179.90.8:8801/delete",
                "http://220.179.90.8:9093/fdss-api/face/delReadCardInfoByCardNo","220.179.90.8"));
        urlList.add(new IpBean("颖泉","http://220.179.82.42:8801/delete",
                "http://220.179.82.42:9093/fdss-api/face/delReadCardInfoByCardNo","220.179.82.42"));
        urlList.add(new IpBean("广德","http://60.173.82.157:8801/delete",
                "http://60.173.82.157:9093/fdss-api/face/delReadCardInfoByCardNo","60.173.82.157"));
        urlList.add(new IpBean("怀远","http://218.22.94.164:8801/delete",
                "http://218.22.94.164:9093/fdss-api/face/delReadCardInfoByCardNo","218.22.94.164"));
        urlList.add(new IpBean("颍州","http://220.180.153.108:8801/delete",
                "http://220.180.153.108:9093/fdss-api/face/delReadCardInfoByCardNo","220.180.153.108"));
        urlList.add(new IpBean("潜山","http://183.161.35.44:8801/delete",
                "http://183.161.35.44:9093/fdss-api/face/delReadCardInfoByCardNo","183.161.35.44"));
        urlList.add(new IpBean("测试地址","http://192.168.45.241:8801/delete",
                "http://192.168.45.241:9093/fdss-api/face/delReadCardInfoByCardNo","192.168.45.241"));
        SharedPreferences sp = getActivity().getSharedPreferences("SP_IPBEAN_List",Activity.MODE_PRIVATE);//创建sp对象,如果有key为"SP_PEOPLE"的sp就取出
        Gson gson = new Gson();
        String jsonStr=gson.toJson(urlList); //将List转换成Json
        String   peopleListJson = sp.getString("KEY_PEOPLE_LIST_DATA",jsonStr);  //取出key为"KEY_PEOPLE_DATA"的值，如果值为空，则将第二个参数作为默认值赋值
        if(peopleListJson!="")  //防空判断
        {
            Gson gson1 = new Gson();
            urlList = gson1.fromJson(peopleListJson, new TypeToken<List<IpBean>>() {}.getType()); //将json字符串转换成List集合
        }


        btnDeleteArchive=(Button)view.findViewById(R.id.btn_delete_archive);
        etIdCardToDelete=(EditText)view.findViewById(R.id.et_id_card_to_delete);
        ip_address=(TextView)view.findViewById(R.id.ip_address);
        btn_delete_time=(Button)view.findViewById(R.id.btn_delete_time);
        btn_add_area=(Button)view.findViewById(R.id.btn_add_area);
        ip_time=(TextView)view.findViewById(R.id.ip_time);
        btn_ip_list=(Button)view.findViewById(R.id.btn_ip_list);
        btn_add_area.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });




//        btn_ip_list.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dialog.show();// 显示对话框
//                // 将对话框的大小按屏幕大小的百分比设置
//                WindowManager windowManager =getWindowManager();
//                Display display = windowManager.getDefaultDisplay();
//                WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
//                lp.width = (int) (display.getWidth() * 0.6); //设置宽度
//                dialog.getWindow().setAttributes(lp);
//            }
//        });
        btnDeleteArchive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.Theme_AppCompat_Light_Dialog_Alert);
                builder.setTitle("温馨提示");
                builder.setMessage("确定删除   "+etIdCardToDelete.getText().toString()+"  人脸档案吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(BasePhoptoRunnable).start();
                    }});

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                AlertDialog dialog =builder.create();
                dialog.setCancelable(true);
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();

            }
        });
        item=new String[urlList.size()];
        for (int i=0;i<urlList.size();i++){
            item[i]= urlList.get(i).getAddress();
        }

        ip_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                item=new String[urlList.size()];
                for (int i=0;i<urlList.size();i++){
                    item[i]= urlList.get(i).getAddress();
                }
                AlertDialog dialog = new AlertDialog.Builder(getActivity(),R.style.Theme_AppCompat_Light_Dialog_Alert).setTitle("请选择")
                        .setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                url=urlList.get(which).getIp();
                                ip_address.setText("已选择"+urlList.get(which).getAddress()+urlList.get(which).getSip());

                                dialog.dismiss();

                            }
                        }).create();
                dialog.show();
            }
        });

        /**
         * 有效期
         * */
        ip_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                item=new String[urlList.size()];
                for (int i=0;i<urlList.size();i++){
                    item[i]= urlList.get(i).getAddress();
                }
//                items.toArray(item);
                AlertDialog dialog = new AlertDialog.Builder(getActivity(),R.style.Theme_AppCompat_Light_Dialog_Alert).setTitle("请选择")
                        .setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                timeurl=urlList.get(which).getTimeurl();
                                ip_time.setText("(有效期)已选择"+urlList.get(which).getAddress()+urlList.get(which).getSip());

                                dialog.dismiss();

                            }
                        }).create();
                dialog.show();
            }
        });

        btn_delete_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(netReadCard).start();
            }
        });
        return view;
    }
    String DeleteBasePhotoMessage,DeleteTimeMessage;
    /**
     * 删除有效期
     */
    private void deleteTime(){

     String DeleteBitmapUrl="http://192.168.45.241:9098/WebService/Andrews/SaveFaceRecognitionDay.asmx";
       String methodName="DeleteWPReadCardInfo" ;
        String idCardNumber =etIdCardToDelete.getText().toString();
        if ( TextUtils.isEmpty(idCardNumber)||TextUtils.isEmpty(timeurl)){
            myhandler.sendEmptyMessage(1);

        }else {
            JSONObject data = new JSONObject();
            try {
                data.put("sCardNo",idCardNumber);
//                data.put("sPersonID",sPersonID);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            String  content = WebServiceUtils.requestByParams(methodName,
                    data.toString(), DeleteBitmapUrl);
            if (!TextUtils.isEmpty(content)) {
                JSONObject json = null;
                try {
                    json = new JSONObject(content);
                    int isSuccess = json.getInt("sSuccess");
                    DeleteTimeMessage = json.getString("sMessage");
                    myhandler.sendEmptyMessage(DELETETIME_MESSAGE);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }



            myhandler.sendEmptyMessage(0);
  }

    }

    private Runnable BasePhoptoRunnable = new Runnable() {
        @Override
        public void run() {
            deleteArchive();
        }
    };

    private Runnable netReadCard = new Runnable() {
        @Override
        public void run() {
            deleteTime();
        }
    };
    public static Object JSONToObject(String json,Class beanClass) {
        Gson gson = new Gson();
        Object res = gson.fromJson(json, beanClass);
        return res;
    }
    /**
     * 删除人脸档案
     */

    private void deleteArchive(){

        String DeleteBitmapUrl="http://192.168.45.241:9098/WebService/Andrews/SaveFaceRecognitionDay.asmx";
        String methodName="DeleteRecognitionBasePhoto" ;
        String idCardNumber =etIdCardToDelete.getText().toString();
        if ( TextUtils.isEmpty(idCardNumber)||TextUtils.isEmpty(url)){
            myhandler.sendEmptyMessage(1);

        }else {
            JSONObject data = new JSONObject();
            try {
                data.put("sCardNo",idCardNumber);
//                data.put("sPersonID",sPersonID);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            String  content = WebServiceUtils.requestByParams(methodName,
                    data.toString(), DeleteBitmapUrl);
            if (!TextUtils.isEmpty(content)) {
                JSONObject json = null;
                try {
                    json = new JSONObject(content);
                    int isSuccess = json.getInt("sSuccess");
                    DeleteBasePhotoMessage = json.getString("sMessage");
                    myhandler.sendEmptyMessage(DELETEBASEPHOTO_MESSAGE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }



            myhandler.sendEmptyMessage(0);
        }


    }
    AlertDialog dialogPhone;
    private void showDialog() {
        final EditText edit_newname, edit_newip1,edit_newip2,edit_newip3,edit_newip4;

        LayoutInflater inflater = LayoutInflater.from(getContext());
        View view = inflater.inflate(R.layout.add_newarea_layout, null);
        edit_newname = (EditText) view.findViewById(R.id.edit_newname);
        edit_newip1 = (EditText) view.findViewById(R.id.edit_newip1);
        edit_newip2 = (EditText) view.findViewById(R.id.edit_newip2);
        edit_newip3 = (EditText) view.findViewById(R.id.edit_newip3);
        edit_newip4 = (EditText) view.findViewById(R.id.edit_newip4);




        dialogPhone = new AlertDialog.Builder(getContext()).setPositiveButton("确定", null).setNegativeButton("取消", null).create();
        dialogPhone.setTitle("添加新地址");// 设置标题
        dialogPhone.setView(view);
        dialogPhone.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Button positionButton = dialogPhone.getButton(AlertDialog.BUTTON_POSITIVE);
                Button negativeButton = dialogPhone.getButton(AlertDialog.BUTTON_NEGATIVE);
                positionButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!TextUtils.isEmpty(edit_newip1.getText().toString())&&
                                !TextUtils.isEmpty(edit_newip2.getText().toString())&&
                                !TextUtils.isEmpty(edit_newip3.getText().toString())&&
                                !TextUtils.isEmpty(edit_newip4.getText().toString())
                                ) {
                            String newip1 = edit_newip1.getText().toString();
                            String newip2 = edit_newip2.getText().toString();
                            String newip3 = edit_newip3.getText().toString();
                            String newip4 = edit_newip4.getText().toString();

                            String newname=  edit_newname.getText().toString();
                            String newip=newip1+"."+newip2+"."+newip3+"."+newip4;
                            urlList.add(new IpBean(newname,"http://"+newip+":"+"8801"+"/delete",
                                    "http://"+newip+":"+"9093"+"/fdss-api/face/delReadCardInfoByCardNo",newip));
//                            items.add(newname);

                            SharedPreferences sp = getActivity().getSharedPreferences("SP_IPBEAN_List",Activity.MODE_PRIVATE);//创建sp对象
                            Gson gson = new Gson();
                            String jsonStr=gson.toJson(urlList); //将List转换成Json
                            SharedPreferences.Editor editor = sp.edit() ;
                            editor.putString("KEY_PEOPLE_LIST_DATA", jsonStr) ; //存入json串
                            editor.apply() ;  //提交
                            dialogPhone.dismiss();
                        } else {
                            Toast.makeText(getActivity(), "不可以为空", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                negativeButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "取消", Toast.LENGTH_SHORT).show();
                        dialogPhone.dismiss();
                    }
                });
            }
        });

        dialogPhone.show();


    }

    public static String getOriginalToken(long timestamp){
//        long timestamp = getTimeStamp();
        String result ="jqsoft892155892138"+timestamp;
        return result;
    }
    public static String getProcessedToken(long timestamp){
        String raw = getOriginalToken(timestamp);
        String result = Md5Tool.hashKey(raw);
        return result;
    }
    public static long getTimeStamp(){
        long acsTime = System.currentTimeMillis();
        return acsTime;
    }
    private final int DELETETIME_MESSAGE=2;
    private final int DELETEBASEPHOTO_MESSAGE=3;
    private Handler myhandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(),message,Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(getActivity(),"身份证号和地址不能为空!",Toast.LENGTH_SHORT).show();
                    break;
                case DELETETIME_MESSAGE:
                    Toast.makeText(getActivity(),DeleteTimeMessage,Toast.LENGTH_SHORT).show();
                    break;
                case DELETEBASEPHOTO_MESSAGE:
                    Toast.makeText(getActivity(),DeleteBasePhotoMessage,Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };
}
